package com.imgo.max.fans.service;

import com.imgo.max.artist.constant.FansConstant;
import com.imgo.max.artist.redis.FansRedisDao;
import com.imgo.max.cache.util.CacheCommonManager;
import com.imgo.max.common.log.CustomLogger;
import com.imgo.max.common.log.CustomLoggerFactory;
import com.imgo.max.common.result.ModuleResultCode;
import com.imgo.max.common.util.LoggerUtils;
import com.imgo.max.fans.listener.FansMsgHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by ben on 16/3/13.
 */
@Service("fansRedisDao")
public class FansRedisDaoImpl implements FansRedisDao {
	private static final CustomLogger logger = CustomLoggerFactory.getLogger(FansRedisDaoImpl.class);

	@Autowired
	private CacheCommonManager cacheCommonManager;
	@Autowired
	private FansMsgHandler fansMsgHandler;

	@Override
	public Integer getFansNum(String artistId) {
		Long fansNum = fansMsgHandler.getFansIdsSize(artistId);
		return fansNum != null ? fansNum.intValue() : 0;
	}

	/**
	 * 获取粉丝增量值
	 * @param artistUid
	 * @return
	 */
	public Integer getFansIncrement(String artistUid) {
		String redisKey = FansConstant.REDIS_ARTIST_FANS_INCREMENT_PREFIX + artistUid;
		String incrementStr = cacheCommonManager.getValue(redisKey, CacheCommonManager.RedisTemplateEnum.STRINGSERIALIZER);
		Integer increNum = 0;
		if (StringUtils.isBlank(incrementStr)) {
			cacheCommonManager.setValueAndExpire(redisKey, "0", CacheCommonManager.RedisTemplateEnum.STRINGSERIALIZER, -1);
		} else {
			increNum = Integer.parseInt(incrementStr);
		}

		return increNum;
	}
	
	/**
	 * 更新粉丝增量值
	 * @param artistUid
	 * @param increNum
	 */
	public void updateFansIncrement(String artistUid, int increNum) {
		try {
			String redisKey = FansConstant.REDIS_ARTIST_FANS_INCREMENT_PREFIX + artistUid;
			cacheCommonManager.increment(redisKey, increNum);
		} catch (Exception e) {
			LoggerUtils.error(logger, e, ModuleResultCode.FANS, artistUid, increNum);
		}
	}
	
	/**
	 * 更新粉丝数量
	 * @param artistUid
	 * @param isIncrease
	 */
	public void updateFansNum(String artistUid, boolean isIncrease) {
		long delta = -1;
		if (isIncrease) {
			delta = 1;
		}
		try {
			String key = FansConstant.REDIS_ARTIST_FANS_NUM_PREFIX + artistUid;
			cacheCommonManager.increment(key, delta);
		} catch (Exception e) {
			LoggerUtils.error(logger, e, ModuleResultCode.FANS, artistUid, isIncrease);
		}
	}

}
